'use strict';
(function(){
  function text(el){ return (el && (el.textContent||el.innerText)||'').trim(); }
  function textById(id){ return text(document.getElementById(id)); }
  function currentLicense(){
    var active = document.querySelector('.plans li.active') || document.querySelector('.plans li');
    if(!active) return '';
    var span = active.querySelector('span');
    return text(span) || text(active);
  }
  function getTitle(){ return textById('tp-title') || textById('lm-track-title') || text(document.querySelector('[data-track-title]')) || '已选曲目'; }
  function getArtist(){ return textById('tp-artist') || textById('lm-artist') || text(document.querySelector('[data-track-artist]')) || ''; }
  function gotoCheckout(){
    try{
      var title = getTitle();
      var artist = getArtist();
      var license = currentLicense() || '个人授权';
      var params = new URLSearchParams();
      params.set('title', title);
      params.set('artist', artist);
      params.set('license', license);
      location.href='checkout.html?' + params.toString();
    }catch(e){
      console.error('checkout-bridge error', e);
      location.href='checkout.html';
    }
  }
  function handleClick(ev, el){
    // Match by id or text label
    var id = el && el.id;
    var label = text(el).replace(/\s+/g,'');
    if(id === 'tp-cart' || id === 'lm-add-cart' || /加入购物车/.test(label)){
      ev.preventDefault();
      gotoCheckout();
      return true;
    }
    return false;
  }
  function bind(){
    var cartBtn = document.getElementById('tp-cart');
    if(cartBtn){ cartBtn.addEventListener('click', function(ev){ handleClick(ev, cartBtn); }); }
    var modalCartBtn = document.getElementById('lm-add-cart');
    if(modalCartBtn){ modalCartBtn.addEventListener('click', function(ev){ handleClick(ev, modalCartBtn); }); }
    // Delegate clicks site-wide for safety
    document.addEventListener('click', function(ev){
      var el = ev.target;
      // bubble up a few levels to catch button wrappers
      for(var i=0;i<4 && el;i++, el=el.parentElement){
        if(el.tagName === 'BUTTON' || el.tagName === 'A'){
          if(handleClick(ev, el)) break;
        }
      }
    }, { passive:false });
  }
  if(document.readyState === 'loading'){
    document.addEventListener('DOMContentLoaded', bind, { once:true });
  }else{
    bind();
  }
})();
